package cn.oracle.eshop.comment.schedule;

import cn.hutool.core.collection.CollUtil;
import cn.oracle.eshop.comment.domain.CommentInfoDTO;
import cn.oracle.eshop.comment.service.CommentAggregateService;
import cn.oracle.eshop.comment.service.CommentInfoService;
import cn.oracle.eshop.order.domain.OrderInfoDTO;
import cn.oracle.eshop.order.domain.OrderItemDTO;
import cn.oracle.eshop.order.service.OrderFacadeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自动发表评论的调度任务
 *
 * @author wyh
 * @ClassName AutoPublishCommentTask
 * @date 2022/1/25 /23:15
 */
@Component
@Slf4j
public class AutoPublishCommentTask {
    /***
     *  订单中心的service组件
     * @author wyh
     * @date 2022/2/9
     * @param null
     * @return
     */

    @Autowired
    private OrderFacadeService orderFacadeService;

    /**
     * 评论信息管理模块的service组件
     */
    @Autowired
    private CommentInfoService commentInfoService;
    /**
     * /**
     * 评论统计信息管理模块的service组件
     */
    @Autowired
    private CommentAggregateService commentAggregateService;

    /**
     * 每隔10分钟检查一次
     */
    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void execute() {

        try {
            //先从订单中心查询确认时间超过7天，而且还没有发表评论的订单
            List<OrderInfoDTO> orderInfoDTOS = orderFacadeService.listNotPublishedCommentOrders();
            if (CollUtil.isNotEmpty(orderInfoDTOS)) {
                List<Long> orderInfoIds = new ArrayList<>(orderInfoDTOS.size());
                //遍历所有的订单
                if (CollUtil.isNotEmpty(orderInfoDTOS)) {
                    for (OrderInfoDTO orderInfoDTO : orderInfoDTOS) {
                        if (CollUtil.isEmpty(orderInfoDTO.getOrderItems())) {
                            continue;
                        }
                        orderInfoIds.add(orderInfoDTO.getId());
                        //遍历订单中的订单项
                        for (OrderItemDTO orderItemDTO : orderInfoDTO.getOrderItems()) {
                            //先保存自动发表的评论信息
                            CommentInfoDTO commentInfoDTO = commentInfoService.saveAutoPublishedCommentInfo(orderInfoDTO, orderItemDTO);
                            //更新评论统计信息
                            commentAggregateService.updateCommentAggregate(commentInfoDTO);

                        }
                    }
                }
                //通知订单中心，批量对那些订单发表了评论
                orderFacadeService.informBatchPublishCommentEvent(orderInfoIds);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

    }
}
